package com.example.oschina.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.oschina.R
import com.example.oschina.databinding.ActivityLoginBinding
import com.example.oschina.network.mode.TokenMode
import com.example.oschina.network.sync.OschinaService
import com.example.oschina.utils.Utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


/**
 * A login screen that offers login via email/password.
 */
class LoginActivity : AppCompatActivity() {
  private lateinit var activityLoginBinding: ActivityLoginBinding

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    activityLoginBinding =
        DataBindingUtil.inflate(layoutInflater, R.layout.activity_login, null, false)
    setContentView(activityLoginBinding.root)

    activityLoginBinding.emailSignInButton.setOnClickListener {
      Utils.startLoginOsChina(this@LoginActivity)
    }
  }

  private fun getTokenTask(codes: String) {
    GlobalScope.launch(Dispatchers.Main) {
      val retrofit = Utils.getDefaultRetrofit()

      val service = retrofit.create<OschinaService>(OschinaService::class.java)
      val response =
        withContext(Dispatchers.Default) { service.getToken(code = codes).execute() }
      if (response.isSuccessful) {
        val result: TokenMode? = response.body()
        Log.e(TAG, "token :$result")
      } else {
        Log.e(TAG, "code ${response.code()} msg:${response.message()}")
      }
    }
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    val code = Utils.getCodeFromIntent(requestCode, resultCode, data)
    Log.e(TAG, "code :$code");
    getTokenTask(code)
  }

  companion object {

    /**
     * Id to identity READ_CONTACTS permission request.
     */
    private val REQUEST_READ_CONTACTS = 0
    private val TAG = LoginActivity::class.java.simpleName
  }
}
